package com.sky.interceptor;

import cn.hutool.core.util.StrUtil;
import com.sky.constant.JwtClaimsConstant;
import com.sky.context.BaseContext;
import com.sky.properties.JwtProperties;
import com.sky.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * jwt令牌校验的拦截器
 */
@Component
@Slf4j
public class JwtTokenAdminInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 校验jwt
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }

        //1.从请求头中获取token,并解析
        String token = request.getHeader("token");

        //2.如果没有Token，响应401
        if (StrUtil.isBlank(token)) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }

        //3.继续有Token但解析失败，响应401
        Claims claimsBody = JwtUtil.getClaimsBody(token);
        int i = JwtUtil.verifyToken(claimsBody);
        if (i == 1 || i == 2) {//表示过期了
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }

        //4.方形请求前获取Token里的员工ID，设置到ThreadLocal中
        Object employeeIdObj = claimsBody.get("id");
        Long employeeId = Long.valueOf(String.valueOf(employeeIdObj));
        BaseContext.setCurrentId(employeeId);

        //5.如果Token解析成功，放行请求
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清理ThreadLocal数据，避免出现OOM问题
        BaseContext.removeCurrentId();
    }
}
